import 'package:flutter/material.dart';
import 'dart:async';
import 'package:dio/dio.dart';
//import 'package:path_provider/path_provider.dart';
import 'package:aweb5/config/Config.dart';
class HttpPlugin {
  static HttpPlugin _instance;
  HttpPlugin._();
  Dio dio;
  static HttpPlugin get instance {
    return _getInstance();
  }

  static HttpPlugin _getInstance() {
    if (_instance == null) {
      _instance = new HttpPlugin._();
      _instance._init();
    }
    return _instance;
  }

  _init() {
    BaseOptions options = new BaseOptions(
//      baseUrl: "http://mobile-api.dev.666pay.vip",
      baseUrl: Config.baseUrl,
      connectTimeout: 5000,
      receiveTimeout: 5000,
    );
    this.dio = new Dio(options);
    this.dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
          print(options.path);

   //   String token =  Application.sharedPreferences.get(EnumSp.accessToken.toString());
//      if(token != null){
//        options.headers['access-token'] = token;
//      }
      // Do something before request is sent
      return options; //continue
      // If you want to resolve the request with some custom data，
      // you can return a `Response` object or return `dio.resolve(data)`.
      // If you want to reject the request with a error message,
      // you can return a `DioError` object or return `dio.reject(errMsg)`
    }, onResponse: (Response response) {
      // Do something with response data
      print("res: " + response.toString());
      if (response.data['Success'] == '1') {
        return dio.resolve(response.data);
      }

      DioError dioError =  new DioError(response: response);
      return dio.reject(dioError);
    }, onError: (DioError e) {
      if (e.response != null) {
        if(e.response.statusCode == 401){
//          Application.sharedPreferences.remove(EnumSp.accessToken.toString());
//          Application.router.navigateTo(Application.context, "/login", clearStack: true);
        }
        print("res error: " +  e.response.request.path);
      }

      return e;
    }));
  }

  Future get(String url, {Map<String, dynamic> params}) async {
    Response response = await this.dio.get(url, queryParameters: params);
    return response.data;
  }

  Future post(String url, dynamic params) async {
    Response response = await this.dio.post(url, data: params);
    return response.data;
  }

//  Future download(String url) async {
//    Dio dio = Dio();
//
//    var dirToSave = await getApplicationDocumentsDirectory();
//    String path="${dirToSave}/${DateTime.now().millisecondsSinceEpoch}.png";
//    await dio.download(url, "${dirToSave.path}/myImage.jpg",
//        onReceiveProgress: (rec, total) {
//
//        });
//
//
//    return "";
//  }

}